package cn.xu.bookstore.category.service;

import java.util.List;

import cn.xu.bookstore.book.dao.BookDao;
import cn.xu.bookstore.category.dao.CategoryDao;
import cn.xu.bookstore.category.domain.Category;
import cn.xu.bookstore.category.exception.CategoryException;

public class CategoryService {
	
	private CategoryDao categoryDao = new CategoryDao();
	private BookDao bookDao = new BookDao();
	
	public List<Category> findAll(){
		return categoryDao.findAll();
	}

	public Category load(String cid) {
		
		return categoryDao.findBycid(cid);
	}

	public void edit(Category category) {
		
		categoryDao.updateCategory(category);
	}

	/*
	 * 添加 分类名称 不能添加 重复的名称
	 */
	public void add(Category category)throws CategoryException {
		List<Category> categorys  = categoryDao.findAll();
		Boolean flag = false;
		for(Category c : categorys){
			if(c.getCname().equals(category.getCname())){
				flag  = true;
				break;
			}
		}
		
		if(flag) throw new CategoryException("添加的分类名有重复，请重新添加");
		
		categoryDao.add(category);
	}
	
	public void delete(String cid) throws CategoryException{
		/*
		 * 如果该分类下图书 则不能删除 抛出异常
		 */
		int count = bookDao.getCountByCid(cid);
		if(count >0){
			throw new CategoryException("该分类不能删除！");
		}
		
		categoryDao.delete(cid);
	}

}
